package com.company.gobang.core;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.netty.buffer.ByteBuf;
import xyz.noark.core.lang.ByteArray;
import xyz.noark.core.lang.ImmutableByteArray;
import xyz.noark.core.lang.StringByteArray;
import xyz.noark.core.network.NetworkPacket;
import xyz.noark.core.network.NetworkProtocol;
import xyz.noark.network.codec.DefaultNetworkPacket;
import xyz.noark.network.codec.json.SimpleJsonCodec;
import xyz.noark.network.util.ByteBufUtils;

/**
 * 简单的JSON协议解析器.
 * <p>由于客户端是借的别人的，所以协议解析需要靠普别的定义，就不要问我为什么要这样设定封包的结构了</p>
 *
 * @author 小流氓[176543888@qq.com]
 */
public class SimpleJsonCodecV2 extends SimpleJsonCodec {

    @Override
    public NetworkPacket decodePacket(ByteBuf byteBuf) {
        // 由于备选的客户端把协议与封包内容放一起了，那就提前解析所有内容吧
        byte[] bytes = ByteBufUtils.readBytes(byteBuf);
        JSONObject object = JSON.parseObject(new String(bytes));

        DefaultNetworkPacket packet = new DefaultNetworkPacket();
        packet.setLength(bytes.length);
        packet.setOpcode(object.getString("type"));
        packet.setBytes(new ImmutableByteArray(bytes));
        return packet;
    }

    @Override
    public <T> T decodeProtocol(ByteArray bytes, Class<T> klass) {
        // 这里就用原来的Json解析功能就行了
        return super.decodeProtocol(bytes, klass);
    }

    @Override
    public ByteArray encodePacket(NetworkProtocol networkProtocol) {
        return new StringByteArray(JSON.toJSONString(networkProtocol.getProtocol()));
    }
}
